package band.wukong.practice.netty.definitiveguide2nd.ch0304;

import band.wukong.practice.netty.Env;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class TimeServer {

    private static final Logger logger;
    static {
        Env.assemblingLog4j2ConfFile();
        logger = LogManager.getLogger();
    }

    private String host;
    private int port;

    public TimeServer(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void bind() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new TimeServerChannelInitializer());

            ChannelFuture f = b.bind(port).sync();
            logger.info("Server started, listening on port {}. ", port);
            f.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            logger.info("Server shutdown.");
        }

    }

    public static void main(String[] args) throws Exception {
        new TimeServer(Env.HOST, Env.PORT).bind();
    }

}


